package com.twang.stock.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.twang.stock.entity.DfcfBanKuaiMaoLiLv;
import com.twang.stock.entity.HotTag;
import com.twang.stock.entity.LongHuInfo;
import com.twang.stock.entity.LongHuInfoXiWei;
import com.twang.stock.entity.ex.LongHuInfoEx;
import com.twang.stock.entity.ex.LongHuInfoXiWeiEx;
import com.twang.stock.mapper.HotTagMapper;
import com.twang.stock.mapper.LongHuInfoMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.LongHuBangService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/")
@Slf4j
public class LongHuBangController {

    @Autowired
    private LongHuBangService longHuBangService;

    @Resource
    private HotTagMapper hotTagMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private LongHuInfoMapper longHuInfoMapper;


    @RequestMapping(value = "/lhb")
    public ModelAndView lhb(LongHuInfo param) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<DfcfBanKuaiMaoLiLv> maoLiLvs =longHuBangService.getLongHuDataList(param);
        modelAndView.addObject("longHuBanglist",maoLiLvs);
        modelAndView.setViewName("lhb/lhb_index");
        return modelAndView;
    }

    private List<LongHuInfoEx> readLongHuBang(LongHuInfo param) {
        List<LongHuInfoEx> result = Lists.newArrayList();
        String longKey = "LHB_CACHE_";
        Example example1 = new Example(LongHuInfo.class);
        example1.orderBy("id").desc();
        String date = longHuInfoMapper.selectByExample(example1).get(0).getDate();
        Object object = redisUtil.get(longKey + date);
        if (null != object) {
            result = JSONObject.parseArray(object.toString(), LongHuInfoEx.class);
        } else {
            List<LongHuInfo> list = longHuBangService.query(param);
            List<LongHuInfoEx> finalResult = result;
            list.stream().forEach(item -> {
                LongHuInfoEx longHuInfoEx = new LongHuInfoEx();
                BeanUtils.copyProperties(item, longHuInfoEx);
                LongHuInfoXiWei xiweiParam = new LongHuInfoXiWei();
                xiweiParam.setLongHuId(item.getId());
                List<LongHuInfoXiWei> dealList = longHuBangService.queryLongXiWei(xiweiParam);
                List<String> buyTag = Lists.newArrayList();//主买
                List<String> saleTag = Lists.newArrayList();//主卖
                List<LongHuInfoXiWeiEx> xiwei = dealList(dealList, buyTag, saleTag);
                longHuInfoEx.setBuyTag(buyTag);
                longHuInfoEx.setSaleTag(saleTag);
                /** 买入前五 */
                LongHuInfoXiWei 买一 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 1 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
                LongHuInfoXiWei 买二 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 2 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
                LongHuInfoXiWei 买三 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 3 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
                LongHuInfoXiWei 买四 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 4 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
                LongHuInfoXiWei 买五 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 5 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
                longHuInfoEx.setMrOne(买一);
                longHuInfoEx.setMrSecond(买二);
                longHuInfoEx.setMrThree(买三);
                longHuInfoEx.setMrFour(买四);
                longHuInfoEx.setMrFive(买五);
                /** 卖出前五 */
                LongHuInfoXiWei 卖一 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 1 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
                LongHuInfoXiWei 卖二 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 2 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
                LongHuInfoXiWei 卖三 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 3 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
                LongHuInfoXiWei 卖四 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 4 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
                LongHuInfoXiWei 卖五 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 5 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
                longHuInfoEx.setMcOne(卖一);
                longHuInfoEx.setMcSecond(卖二);
                longHuInfoEx.setMcThree(卖三);
                longHuInfoEx.setMcFour(卖四);
                longHuInfoEx.setMcFive(卖五);
                finalResult.add(longHuInfoEx);
            });
            // result.addAll(finalResult);
            redisUtil.set(longKey + date,JSONObject.toJSONString(result));
        }
        return result;
    }

    /**
     * @param list
     * @return
     */
    private LongHuInfoXiWei getLongHuInfoXiWei(List<LongHuInfoXiWei> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new LongHuInfoXiWei();
        } else {
            return list.get(0);
        }
    }

    private List<LongHuInfoXiWeiEx> dealList(List<LongHuInfoXiWei> xiwei, List<String> buyTag, List<String> saleTag) {
        List<LongHuInfoXiWeiEx> list = Lists.newArrayList();
        xiwei.forEach(item -> {
            LongHuInfoXiWeiEx longHuInfoXiWeiEx = new LongHuInfoXiWeiEx();
            BeanUtils.copyProperties(item, longHuInfoXiWeiEx);
            String yyb = "";
            yyb = getXiWei(item, buyTag, saleTag);
            longHuInfoXiWeiEx.setYyb(getstrKonggeYYB(yyb, 70));
            //查询营业部
            if ("buy".equals(item.getBuyOrSale())) {
                longHuInfoXiWeiEx.setTradeAmount(getstrKonggeYYB(item.getMrje().toString(), 35));
                longHuInfoXiWeiEx.setTradePercent(item.getMrzzcjb().toString() + "%");
            } else {
                longHuInfoXiWeiEx.setTradeAmount(getstrKonggeYYB(item.getMcje().toString(), 35));
                longHuInfoXiWeiEx.setTradePercent(item.getMczcjb().toString() + "%");
            }
            longHuInfoXiWeiEx.setTradeJe(getstrKonggeYYB(item.getJe().toString(), 35));
            yyb = longHuInfoXiWeiEx.getYyb() + longHuInfoXiWeiEx.getTradeAmount() + longHuInfoXiWeiEx.getTradeJe() + longHuInfoXiWeiEx.getTradePercent();
            longHuInfoXiWeiEx.setYyb(yyb);
            list.add(longHuInfoXiWeiEx);
        });
        return list;
    }

    private String getstrKonggeYYB(String string, int num) {
        int size = new BigDecimal(string.length()).multiply(new BigDecimal(1.87)).intValue();
        String buffer =string;
        for (int i = 0; i < num - size; i++) {
            buffer= buffer+"_";
        }
        return buffer;
    }

    /**
     * 根据营业部查询席位
     * @return
     */
    private String getXiWei(LongHuInfoXiWei xiWei, List<String> buyTag, List<String> saleTag) {
        String yyb = xiWei.getYyb();
        //
        if (StringUtils.isEmpty(yyb)) return "";
        yyb = yyb.replace("股份有限公司", "").replace("证券营业部", "").replace("有限责任公司", "").replace(" ", "");
        Example example = new Example(HotTag.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("hotTemperatureName", yyb.trim());
        List<HotTag> list = hotTagMapper.selectByExample(example);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {
            StringBuffer str = new StringBuffer(yyb).append(" (");
            int size = list.size();
            for (int i = 0; i < size; i++) {
                String tag = list.get(i).getHotTag();
                if (xiWei.getBuyOrSale().equals("buy")) {
                    if (!buyTag.contains(tag)) {
                        buyTag.add(tag);
                    }
                } else {
                    if (!saleTag.contains(tag)) {
                        saleTag.add(tag);
                    }
                }
                if ((i == size - 1 && size > 1) || size == 1) {
                    str.append(list.get(i).getHotTag());
                } else {
                    str.append(list.get(i).getHotTag()).append(",");
                }
            }
            str.append(")");
            return str.toString();
        } else {
            return yyb;
        }
    }
}
